package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.services.ChequeEstadoServices;
import ar.republicagroup.gestion.services.CuentaBancoServices;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.UserSession;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.helpers.UserInterfaceHelper;
import ar.republicagroup.gestion.util.jfreechart.PieChart3D;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.HeadlessException;
import java.awt.print.PrinterException;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class FrmReporteCuentaPorFechas extends javax.swing.JFrame {

    private static FrmReporteCuentaPorFechas instance;
    private static Logger log = Logger.getLogger(FrmReporteCuentaPorFechas.class);
    private double importeTotal;
    
    Map<String,Object> result;
    
    private FrmReporteCuentaPorFechas() {
        initComponents();
        valoresPorDefecto();
    }
    
    public static FrmReporteCuentaPorFechas getInstance(){
    
        if (instance == null){
            instance = new FrmReporteCuentaPorFechas();
        }
    
        return instance;
    }
    
    
    
    private void valoresPorDefecto(){
        UserInterfaceHelper.setTitleToThisJFrame(this, "Estado de cuenta por fechas");
        UserInterfaceHelper.setJFrameIconImage(this);
        Calendar beginMonth = Calendar.getInstance();
        beginMonth.set(Calendar.DAY_OF_MONTH, 1);
        jCalendarDesde.setDate(beginMonth.getTime());
        jCalendarHasta.setDate(new Date());
    }
    
    public void cargarTablaCuentaPorFechas(){
        
        Date fechaIni = jCalendarDesde.getDate();
        Date fechaFin = jCalendarHasta.getDate();
        
        CuentaBancoServices cuentaBancoServices = (CuentaBancoServices)SpringUtils.getBean("cuentaBancoServices");
        result = cuentaBancoServices.getTotalesPorCuentaByEstadoAndDates(ChequeEstadoServices.CHEQUE_LIQUIDADO, fechaIni, fechaFin);
        
        DefaultTableModel model = (DefaultTableModel) tblCuentaPorFechas.getModel();
        model.getDataVector().clear();
        importeTotal = 0;
        
        for(Map.Entry<String,Object> row : result.entrySet()){
            String cuentaBanco = row.getKey().toString();
            double importe = Double.parseDouble(row.getValue().toString());
            importeTotal += importe ;
            String totalString = Formato.decimalComaMilesConSigno(importe);
            model.addRow(new Object[]{ cuentaBanco , totalString });
        }
        
        tblCuentaPorFechas.setModel(model);
        tblCuentaPorFechas.repaint();
        
        lblTotalImporte.setText(Formato.decimalComaMilesConSigno(importeTotal));
        
        
    }
    

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jCalendarDesde = new com.toedter.calendar.JDateChooser();
        jCalendarHasta = new com.toedter.calendar.JDateChooser();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCuentaPorFechas = new javax.swing.JTable();
        btnBuscar = new javax.swing.JButton();
        btnImprimir = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lblTotalImporte = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Desde");

        jLabel2.setText("Hasta");

        tblCuentaPorFechas.setAutoCreateRowSorter(true);
        tblCuentaPorFechas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cuenta", "Importe cheques"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblCuentaPorFechas);

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/search.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jCalendarHasta, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(43, 43, 43)
                        .addComponent(btnBuscar))
                    .addComponent(jCalendarDesde, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(100, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jCalendarDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(jCalendarHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/printer.png"))); // NOI18N
        btnImprimir.setText("Imprimir");
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        jLabel3.setText("Total importe :");

        lblTotalImporte.setText("0");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/piechart_16x16.png"))); // NOI18N
        jButton1.setText("Gráfica");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(lblTotalImporte)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnImprimir)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnImprimir, jButton1});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnImprimir)
                    .addComponent(jLabel3)
                    .addComponent(lblTotalImporte)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnImprimir, jButton1});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        
        if( jCalendarDesde.getDate().before( jCalendarHasta.getDate() ) ) {
            cargarTablaCuentaPorFechas();
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("futureDateSelected"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            Calendar beginMonth = Calendar.getInstance();
            beginMonth.set(Calendar.DAY_OF_MONTH, 1);
            jCalendarDesde.setDate(beginMonth.getTime());
        }
              
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        
         try {
            
            SimpleDateFormat formatDate = new SimpleDateFormat(jCalendarDesde.getDateFormatString());
            String msj =  MessageFormat.format(UIMessages.getInfoMessage("estadoCuentaPorFecha_title"), formatDate.format(jCalendarDesde.getDate()),formatDate.format(jCalendarHasta.getDate()));
            MessageFormat header = new MessageFormat(msj,new Locale("es","ES"));
            
            /* Agregamos el total al reporte antes de enviarlo a imprimir */
            DefaultTableModel model = (DefaultTableModel)tblCuentaPorFechas.getModel();
            model.addRow(new Object[]{"Total",Formato.decimalComaMilesConSigno(importeTotal)});
            
            boolean imprimio = tblCuentaPorFechas.print(JTable.PrintMode.NORMAL, header, null, true, null, true);
             
                if(imprimio){
                    log.info(UserSession.getInstance().getUser_name()+ "--->"+" imprimiendo estadoCuentaPorFecha");
                }
                
            } catch (PrinterException ex) {
                log.error("Error al imprimir...",ex);
                log.error(ex.getMessage());
            } catch (HeadlessException ex) {
                log.error(ex.getMessage());
                log.error("Sin encabezado ...",ex);
            }
        
        
        
        
    }//GEN-LAST:event_btnImprimirActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
         PieChart3D demo = new PieChart3D(result,UIMessages.getInfoMessage("graphPieChart1"));
         demo.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         demo.pack();
         UserInterfaceHelper.centreWindow(demo);
         //RefineryUtilities.centerFrameOnScreen(demo);
         demo.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    
    
    
    public static void main(String args[]) {
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmReporteCuentaPorFechas().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton jButton1;
    private com.toedter.calendar.JDateChooser jCalendarDesde;
    private com.toedter.calendar.JDateChooser jCalendarHasta;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblTotalImporte;
    private javax.swing.JTable tblCuentaPorFechas;
    // End of variables declaration//GEN-END:variables
}
